package org.afk.sisy.io;

import java.util.concurrent.*;

import org.afk.sisy.*;
import org.afk.tools.log.*;

public class SisyCompareResultProcessor extends Thread
{
	private final ExecutorService executorService;
	private final LinkedBlockingQueue<Future<CopyJob>> todo = new LinkedBlockingQueue<Future<CopyJob>>();
	private final ErrorHandler errorHandler;
	private boolean finished;

	public SisyCompareResultProcessor(final ExecutorService executorService, final ErrorHandler errorHandler)
	{
		super();
		this.executorService = executorService;
		this.errorHandler = errorHandler;
	}

	public void add(final Callable<CopyJob> job) throws InterruptedException
	{
		todo.put(executorService.submit(job));
	}

	@Override
	public void run()
	{
		try
		{
			for (;;)
			{
				final Future<CopyJob> poll = todo.poll(1, TimeUnit.SECONDS);
				if (poll != null)
				{
					final CopyJob copyJob = poll.get();
					if (copyJob != null)
						copyJob.run();
				}
				else if (executorService.isTerminated())
					break;
			}
			finished = true;
		}
		catch (final InterruptedException e)
		{
			errorHandler.warning(e);
		}
		catch (final ExecutionException e)
		{
			errorHandler.warning(e);
		}
	}

	public void waitForEnd() throws InterruptedException
	{
		executorService.shutdown();
		while (!finished)
			Thread.sleep(100);
	}
}
